/*
 * @Author: 丁平|1572804782@qq.com(dingping)
 * @Date: 2021-12-2
 * @LastEditors: 周润玉|zhourunyu1@outlook.com(zhourunyu)
 * @LastEditTime: 2022-07-14 15:00:20
 * @Description: 
 * @Administrator: 师跃|2042289956@qq.com(shiyue)
 * @Copyright: 1.1.5
 */

import DailyApi from '../../../../common/api/pigslaughter/daily.api.js';
import doT from '../../../../../vendor/template/doT.js';
import watermark from '../../../../common/watermark.js';
Utils.NameSpace('SN.CptvPlf.PigSlaughter');
(function (window, document, $) {
    let _vm, pieEcartsData, lineEcartsData;
    $(function () {
        // JS严格模式
        'use strict';
        watermarkBgImg();
        _vm = new Vue({
            el: "#divPage",
            data() {
                return {
					readingUser: []
                }
            },
            async created() {
                let that = this;
                let thisYear = (new Date()).getFullYear(), resData = { bizDate: [], sumAvgPrice: [] };
                DailyApi.getDailyList(getUrlKey("id")).then(async res => {
                    res.total["year"] = thisYear;
                    let _template = doT.template($('#dailyList_template').text());
                    let annualInfo_template = doT.template($('#annualInfo_template').text());
                    $('#annualInfo').append(annualInfo_template(res.total));
                    await res.entries.map(item => {
                        item["bizDate"] = res.bizDate.substring(0,10).replace("/","-").replace("/","-");
						// item["bizDate"] = res.bizDate;
						if(item["oName"] == "云南神农曲靖食品有限公司"){
							item.daily.extendInfos.map(eitem => {
                               if (eitem.sourceValue == "越州食品站") {
                                   item['daily']["spzYZQty"] = eitem.qty;
                               }
                               if (eitem.sourceValue == "东山食品站") {
                                   item['daily']["spzDSQty"] = eitem.qty;
                               }
							})
							item['daily']["spzQJQty"] = item.daily.weighQty;
						}
                        $('#dailyList').append(_template(item));
                    });
                    await res.lastAvgPrice.map(item => {
                        let dataArr = item.bizDate.split(/[-: ]/);
                        resData.bizDate.push(`${dataArr[1]}-${dataArr[2]}`);
                        resData.sumAvgPrice.push(Utils.toThousands(item.sumAvgPrice));
                    })
                    pieEcartsData = resData;
                    lineEcartsData = res.total;
                    pieEcarts(resData);
                    lineEcarts(res.total);
                }).catch(res => {
                    let total = { year: thisYear, curYQty: 0, curYSelfQty: 0, curYAgentQty: 0 };
                    let entries = {
                        oName: "云南神农肉业食品有限公司",
                        bizDate: thisYear,
                        daily: {
                            sumAvgWeight: 0,
                            sumQty: 0,
                            sumAvgPrice: 0,
                            selfQty: 0,
                            selfAvgWeight: 0,
                            selfAvgPrice: 0,
                            agentQty: 0,
                            outQty: 0,
                            agentSltrAvgWeight: 0,
                            agentAvgPrice: 0,
							spzQJQty: 0,
							spzYZQty: 0,
							spzDSQty: 0
                        }
                    };
                    let _template = doT.template($('#dailyList_template').text());
                    let annualInfo_template = doT.template($('#annualInfo_template').text());
                    $('#dailyList').append(_template(entries));
                    $('#annualInfo').append(annualInfo_template(total));
                })
				
				DailyApi.addReadingUser(getUrlKey("id"), {}).then(res => { }).then(_res => {
				    DailyApi.queryReadingUser(getUrlKey("id")).then(res => {
				        that.readingUser = res.split(",");
				    })
				})
            }
        });
        swiperInit();

    });
    const getUrlKey = (name) => { /** 获取地址栏的 参数  传入 字段返回值 */
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    const swiperInit = () => {
        let mySwiper = new Swiper('.swiper-container',
            {
                speed: 1000,//播放速度
                // autoHeight: true,
                loop: false,//循环 最后面一个往后面滑动会滑到第一个
                setWrapperSize: true,
                pagination: {//分页器
                    el: '.swiper-pagination',
                    clickable: true,
                },
                effect: 'slide',//动画效果
                on: {
                    slideChangeTransitionStart: function () {
                        switch (this.activeIndex) {
                            case 1:
                                pieEcarts(pieEcartsData);
                                break;
                            case 2:
                                lineEcarts(lineEcartsData);
                                break;
                        }
                    }
                }
            },
        );
    }
    function pieEcarts(res) {
        let isRotate = document.body.scrollWidth <= 350 ? "-20" : 0;
        var chartDom = document.getElementById('lineAvg');
        var myChart = echarts.init(chartDom);
        var option;
        option = {
            legend: {
                data: ['总均价'],
                x: 'center',
                top: "5%"
            },
            tooltip: {
                trigger: 'axis',
                formatter: function (data) {
                    return `${data[0].axisValue}<br/>${data[0].marker}${data[0].seriesName}&emsp;&emsp;${data[0].value} 元/kg`; //将小数转化为百分数显示
                }
            },
            grid: {
                right: "7%",
                left: "15%"
            },
            xAxis: {
                type: 'category',
                data: res.bizDate,
                axisLabel: {// X轴title倾斜
                    interval: 0,      //坐标轴刻度标签的显示间隔(在类目轴中有效) 0:显示所有  1：隔一个显示一个 :3：隔三个显示一个...
                    rotate: isRotate    //标签倾斜的角度，显示不全时可以通过旋转防止标签重叠（-90到90）
                }
            },
            yAxis: {
                type: 'value',
                scale: true,
                axisLabel: {
                    formatter: function (value, index) {
                        return value.toFixed(1)
                    }
                }
            },
            series: [
                {
                    name: "总均价",
                    data: res.sumAvgPrice,
                    type: 'line',
                    smooth: true,
                    lineStyle: {
                        color: '#73c0de'
                    },
                    itemStyle: {
                        normal: {
                            color: '#73c0de'
                        }
                    }
                }
            ]
        };

        option && myChart.setOption(option);
    }
    function lineEcarts(res) {
        var chartDom = document.getElementById('pieTotalNumber');
        var myChart = echarts.init(chartDom);
        var option;
        option = {
            title: {
                text: '屠宰加工月屠宰量',
                left: 'center',
                y: 'bottom',
                top: "75%"
            },
            tooltip: {
                trigger: 'item',
                formatter: '{b} : {c} 头 ({d}%)'
            },
            grid: {
                y: 100
            },
            series: [
                {
                    type: 'pie',
                    radius: 80,
                    center: ['50%', '37%'],
                    itemStyle: {
                        borderRadius: 5
                    },
                    startAngle: 135, //起始角度
                    label: {
                        normal: {
                            show: true,
                            formatter: '{b}: {c} 头\n({d}%)'
                        }
                    },
                    labelLine: {
                        length: 10, //长度
                        length2: 5 //宽度
                    },
                    data: [
                        {
                            value: res.curMSelfQty, name: '自营', itemStyle: {
                                normal: {
                                    color: "#3e8ef7"
                                }
                            },
                        },
                        {
                            value: res.curMAgentQty, name: '代宰', itemStyle: {
                                normal: {
                                    color: "#73c0de"
                                }
                            }
                        }
                    ]
                }
            ],
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        };

        option && myChart.setOption(option);
    }
    const watermarkBgImg = () => {
        let _userInfo = JSON.parse(Utils.GetSessionStorage("SNLoginUserInfo")) || {};
        DailyApi.queryUserName(Utils.GetQueryString('state') || '').then(res => {
            watermark.set(_userInfo.curUserName + res.code);// 水印
        }).catch(_ => {
            watermark.set(_userInfo.curUserName);// 水印
        });

    }
})(window, document, jQuery);
